package com.ypj.rpc.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 单例工厂
 */
public class SingletonFactory {

    private static Map<Class,Object> map=new HashMap<>();

    private SingletonFactory(){
    }

    public static <T> T getInstance(Class<T> clazz){
        Object instance=map.get(clazz);
        synchronized (clazz){
            if (instance==null){
                try {
                    instance=clazz.newInstance();
                    map.put(clazz,instance);
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return clazz.cast(instance);
    }
}
